
///<reference path="../typings/tsd.d.ts" />
module AUTO {
    export class AjaxButton {
        constructor(element: HTMLButtonElement,fun_def: (p) => JQueryDeferred<any>, fun_para: any) {
             let me = $(this);
            me.off("click").on('click', function(event) {
                if (me.hasClass('disabled')) return;
                me.addClass('disabled ');
                fun_def(fun_para).always(function() {
                    me.removeClass('disabled ');
                });
            });
        }
    }

    export class AutoTimer {
        private $el:JQuery;
        private opt:IAutoTimerOption;
        private tmpl:_.TemplateExecutor;
        private cmd={run:this.run,pause:this.pause,reset:this.reset}
        constructor(element: HTMLElement, options: IAutoTimerOption | string) {
            this.$el= $(element);
            //如果是调用, 不传参，或传入一个object
            if (_.isUndefined(options)|| _.isObject(options)) {
                this.opt = {
                    text: '已执行<%=time%>秒。',
                    interval: 1000  //默认间隔1秒
                }
                $.extend(this.opt, options);
                this.opt.count = 1;
                this.tmpl = _.template(this.opt.text);
                this.opt.timer = setInterval(this.render.bind(this), this.opt.interval);
                this.$el.data('options', this);
            }
            //否则传入的是一个命令
            else{
                let me:AutoTimer=this.$el.data('options');
                me.cmd[<string>options].call(me);
            }
        }
        //输出内容
        private render() {
            this.$el.html(this.tmpl({ time: this.opt.count++ }));
        }
        private pause() {
            if (this.opt.timer) {
                clearInterval(this.opt.timer);
                this.opt.timer = null;
            }
        }
        private run() {
            if (!this.opt.timer) {
                this.opt.timer = setInterval(this.render.bind(this), this.opt.interval);
            }
        }
        private reset() {
            if (this.opt.timer) {
                clearInterval(this.opt.timer);
                this.opt.timer = null;
                this.opt.count = 0;
                this.render();
            }
        }
    }
}